package com.fengye.security.jwt.process;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * 根据用户名获取用户的详细信息
 */
@Component("jwtUserDetailsService")
public class JwtUserDetailsService implements UserDetailsService {

//    private final SysAdminRepository sysAdminRepository;
//
//    private final SysAdminService sysAdminService;
//
//    public JwtUserDetailsService(SysAdminRepository sysAdminRepository, SysAdminService sysAdminService) {
//        this.sysAdminRepository = sysAdminRepository;
//        this.sysAdminService = sysAdminService;
//    }

    @Override
//    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        if (!StringUtils.hasLength(username))
//            throw new UsernameNotFoundException("JwtUserDetailsService, username 不能为空");
//
//        SysAdmin admin = sysAdminService.getAdminByUsername(username);
//        return this.build(admin);

        return User.withUsername("api").password("$2a$10$lO3UJEpV1bStfyeBlrEOHe6El0syC4Ek5hx.hIFiatmWz3RE60c4m").authorities(AuthorityUtils.commaSeparatedStringToAuthorityList("admin,test")).build();
    }

//    @Transactional
//    public UserDetails loadUserById(Long id) throws Exception {
//        Optional<SysAdmin> admin = sysAdminRepository.findById(id);
//        SysAdmin sysAdmin = admin.orElseThrow(() -> new Exception("用户id=" + id + "没找到"));
//        return this.build(sysAdmin);
//    }
//
//    @Transactional
//    public MyUserDetails build(SysAdmin admin) {
//
//        MyUserDetails userDetails = new MyUserDetails();
//        userDetails.setId(admin.getId());
//        userDetails.setUsername(admin.getUsername());
//        userDetails.setPassword(admin.getPassword());
//
//
//        userDetails.setRoles(admin.getRoles().stream().map(SysRole::getName).collect(Collectors.toList()));
//        userDetails.setUserEnabled(((Integer) admin.getStatus()).shortValue());
//
//
//        List<SimpleGrantedAuthority> perms = admin.getRoles().stream().flatMap(r ->
//                r.getPerms().stream().map(p -> new SimpleGrantedAuthority(p.getPermString()))
//        ).collect(Collectors.toList());
//
//        userDetails.setAuthorities(perms);
//        return userDetails;
//    }

}